package com.jingli.pile.converter;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ByteUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jingli.pile.domain.FeeRangeTime;
import com.jingli.pile.domain.TimeRange;
import com.jingli.pile.entity.*;
import com.jingli.pile.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

@Component
public class StationConverter {
    private Logger logger = LoggerFactory.getLogger(StationConverter.class);
    @Autowired
    private XtUserService userService;
    @Autowired
    private SupOperatorInfoService operatorInfoService;
    @Autowired
    private FileService fileService;
    @Value("${service.tel}")
    private String serviceTel;
    @Autowired
    private CustomPriceService customPriceService;
    @Autowired
    private ChargingPileService pileService;
    @Autowired
    private RuleService ruleService;

    public Plot convertStationToPlot(SupStationInfo stationInfo){
        Plot plot = new Plot();
        plot.setId(Integer.valueOf(stationInfo.getStationId()));
        plot.setPlotCode(stationInfo.getStationUniqueNumber());
        plot.setPlotName(stationInfo.getStationName());
        plot.setAddress(stationInfo.getAddress());
        plot.setRegionCode(stationInfo.getStationUniqueNumber().substring(6));
        plot.setUserId("111");
        plot.setCreateTime(new Date());
        plot.setLat(String.valueOf(stationInfo.getStationLat()));
        plot.setLng(String.valueOf(stationInfo.getStationLng()));
        plot.setParkCarInfo(stationInfo.getSiteGuide());
        //todo 文件存储
        plot.setFileId("");
        plot.setDeviceType(4);
        plot.setDelFlag(0);
        return plot;
    }

    public SupStationInfo convertPlotToStationInfo(Plot plot){
        SupStationInfo stationInfo = new SupStationInfo();
        stationInfo.setStationId(String.valueOf(plot.getId()));
        QueryWrapper<SupOperatorInfo> operatorInfoQueryWrapper = new QueryWrapper<>();
        operatorInfoQueryWrapper.eq("user_id",plot.getUserId());
        SupOperatorInfo operatorInfo = operatorInfoService.getOne(operatorInfoQueryWrapper);
        stationInfo.setStationUniqueNumber(plot.getRegionCode()+operatorInfo.getOperatorId()+plot.getId());
        stationInfo.setOperatorId(operatorInfo.getOperatorId());
        stationInfo.setEquipmentOwnerId(operatorInfo.getOperatorId());
        stationInfo.setStationName(plot.getPlotName());
        stationInfo.setCountryCode("CN");
        stationInfo.setAreaCode(plot.getRegionCode());
        stationInfo.setAreaCodeCountryside(plot.getRegionCode()+"000000");
        stationInfo.setAddress(plot.getAddress());
        stationInfo.setStationType(1);
        stationInfo.setStationStatus(50);
        stationInfo.setStationLng(Double.valueOf(plot.getLng()));
        stationInfo.setStationLat(Double.valueOf(plot.getLat()));
        stationInfo.setConstruction(9);
        stationInfo.setParkNum(0);
        stationInfo.setServiceTel(serviceTel);
        stationInfo.setSiteGuide(plot.getParkCarInfo());
        stationInfo.setStationClassification(1);
        stationInfo.setGeneralApplicationType(2);
        stationInfo.setMatchCars("出租车,物流车");
        stationInfo.setParkType(1);
        stationInfo.setPictures("");
        stationInfo.setBusineHours("{\"1\":[\"00:00-24:00\"],\"2\":[\"00:00-24:00\"],\"3\":[\"00:00-24:00\"],\"4\":[\"00:00-24:00\"],\"5\":[\"00:00-24:00\"],\"6\":[\"00:00-24:00\"],\"7\":[\"00:00-24:00\"]}");
        QueryWrapper<ChargingPile> pileQueryWrapper = new QueryWrapper<>();
        pileQueryWrapper.eq("plot",plot.getId());
        pileQueryWrapper.orderByDesc("create_time");
        pileQueryWrapper.last("limit 1");
        QueryWrapper<Rule> ruleQueryWrapper = new QueryWrapper<>();
        ruleQueryWrapper.eq("user_id",plot.getUserId());
        ruleQueryWrapper.eq("is_give",1);
        ruleQueryWrapper.eq("is_sys_give",1);
        ruleQueryWrapper.last("limit 1");
        Rule rule = ruleService.getOne(ruleQueryWrapper);
        JSONObject electricPrice = new JSONObject();
        JSONObject servicePrice = new JSONObject();
        QueryWrapper<CustomPrice> customPriceQueryWrapper = new QueryWrapper<>();
        customPriceQueryWrapper.eq("rule_id",rule.getId());
        List<CustomPrice> priceList = customPriceService.list(customPriceQueryWrapper);
        logger.info("原始列表:{}", JSONObject.toJSONString(priceList));
        if (!CollectionUtil.isEmpty(priceList)){
            if (priceList.size()!=4){
                logger.info("规则列表大小不等于4，deviceId:{}",rule.getId());
            }
            priceList.sort(Comparator.comparing(CustomPrice::getPriceType));
            logger.info("排序后的列表:{}", JSONObject.toJSONString(priceList));
            // 时间段信息
            List<FeeRangeTime> rangeTimeList = new ArrayList<>();
            for (CustomPrice customPrice : priceList) {
                String rangTime = customPrice.getRangTime();
                List<TimeRange> rangeTimes = JSONUtil.toList(rangTime, TimeRange.class);
                for (TimeRange timeRage: rangeTimes) {
                    FeeRangeTime feeRangeTime = new FeeRangeTime();
                    feeRangeTime.setStartTime(convertDecimalToTime(timeRage.getStartTime()));
                    feeRangeTime.setEndTime(convertDecimalToTime(timeRage.getEndTime()));
                    feeRangeTime.setPrice(customPrice.getPrice());
                    feeRangeTime.setServicePrice(customPrice.getServicePrice());
                    feeRangeTime.setPriceType(ByteUtil.intToByte(customPrice.getPriceType()));
                    rangeTimeList.add(feeRangeTime);
                }
            }
            // 按startTime排序rangeTimeList
            rangeTimeList.sort(Comparator.comparing(FeeRangeTime::getStartTime));
            logger.info("最终结果:{}",JSONObject.toJSONString(rangeTimeList));
            for (FeeRangeTime fee :rangeTimeList) {
                electricPrice.put(fee.getStartTime() + "-" + fee.getEndTime(), fee.getPrice().toString());
                servicePrice.put(fee.getStartTime() + "-" + fee.getEndTime(), fee.getServicePrice().toString());
            }
        }
        stationInfo.setElectricityFee(JSONObject.toJSONString(electricPrice));
        stationInfo.setServiceFee(JSONObject.toJSONString(servicePrice));
        stationInfo.setRoundTheClock(1);
        stationInfo.setElectricityType(1);
        stationInfo.setBusinessExpandType(0);
        stationInfo.setRatedPower(4800.0);
        stationInfo.setPrinterFlag(1);
        stationInfo.setOfficialRunTime(DateUtil.formatDate(plot.getCreateTime()));
        stationInfo.setVideoMonitor(1);
        stationInfo.setBuildTime(DateUtil.formatDate(plot.getCreateTime()));
        stationInfo.setPlotId(plot.getId());
        return stationInfo;
    }

    public static String convertDecimalToTime(double decimalTime) {
        int hours = (int) decimalTime;
        int minutes = (int) ((decimalTime - hours) * 60);

        String formattedHours = String.format("%02d", hours);
        String formattedMinutes = String.format("%02d", minutes);

        return formattedHours + ":" + formattedMinutes + ":00";
    }
}
